package com.example.statemachine.service;

import com.example.statemachine.entity.Task;
import com.example.statemachine.core.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class TaskService {

    @Autowired
    private StateMachineTemplate stateMachineTemplate;

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public Task startProcess(Long taskId, String operator, String assignee) {
        Task task = entityManager.find(Task.class, taskId);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }

        Map<String, Object> extraParams = new HashMap<>();
        extraParams.put("assignee", assignee);

        // 修正：传入EventEnum.START_PROCESS
        StateMachineContext context = new StateMachineContext(
                task.getTaskNo(), task.getStatus(), EventEnum.START_PROCESS, operator);
        context.setExtraParams(extraParams);

        TransitionRequest<Task> request = new TransitionRequest<>(
                task.getStatus(),
                EventEnum.START_PROCESS,
                context,
                () -> {
                    Task freshTask = entityManager.find(Task.class, taskId);
                    if (freshTask == null) {
                        throw new StateMachineException("任务不存在: " + taskId);
                    }
                    return freshTask;
                });

        TransitionResult<Task> result = stateMachineTemplate.sendEvent(request, Task.class);

        return result.getEntity();
    }

    @Transactional
    public Task submitApproval(Long taskId, String operator, String approver) {
        Task task = entityManager.find(Task.class, taskId);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }

        Map<String, Object> extraParams = new HashMap<>();
        extraParams.put("approver", approver);

        // 修正：传入EventEnum.SUBMIT_APPROVAL
        StateMachineContext context = new StateMachineContext(
                task.getTaskNo(), task.getStatus(), EventEnum.SUBMIT_APPROVAL, operator);
        context.setExtraParams(extraParams);

        TransitionRequest<Task> request = new TransitionRequest<>(
                task.getStatus(),
                EventEnum.SUBMIT_APPROVAL,
                context,
                () -> {
                    Task freshTask = entityManager.find(Task.class, taskId);
                    if (freshTask == null) {
                        throw new StateMachineException("任务不存在: " + taskId);
                    }
                    return freshTask;
                });

        TransitionResult<Task> result = stateMachineTemplate.sendEvent(request, Task.class);

        return result.getEntity();
    }

    @Transactional
    public Task modifyTask(Long taskId, String operator, String assignee, String description) {
        Task task = entityManager.find(Task.class, taskId);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }

        Map<String, Object> extraParams = new HashMap<>();
        if (assignee != null) {
            extraParams.put("assignee", assignee);
        }
        if (description != null) {
            extraParams.put("description", description);
        }

        // 修正：传入EventEnum.MODIFY
        StateMachineContext context = new StateMachineContext(
                task.getTaskNo(), task.getStatus(), EventEnum.MODIFY, operator);
        context.setExtraParams(extraParams);

        TransitionRequest<Task> request = new TransitionRequest<>(
                task.getStatus(),
                EventEnum.MODIFY,
                context,
                () -> {
                    Task freshTask = entityManager.find(Task.class, taskId);
                    if (freshTask == null) {
                        throw new StateMachineException("任务不存在: " + taskId);
                    }
                    return freshTask;
                });

        TransitionResult<Task> result = stateMachineTemplate.sendEvent(request, Task.class);

        return result.getEntity();
    }

    @Transactional
    public Task approveTask(Long taskId, String operator) {
        Task task = entityManager.find(Task.class, taskId);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }

        // 修正：传入EventEnum.APPROVE
        StateMachineContext context = new StateMachineContext(
                task.getTaskNo(), task.getStatus(), EventEnum.APPROVE, operator);

        TransitionRequest<Task> request = new TransitionRequest<>(
                task.getStatus(),
                EventEnum.APPROVE,
                context,
                () -> entityManager.find(Task.class, taskId));

        TransitionResult<Task> result = stateMachineTemplate.sendEvent(request, Task.class);

        return result.getEntity();
    }

    @Transactional
    public Task rejectTask(Long taskId, String operator, String rejectReason) {
        Task task = entityManager.find(Task.class, taskId);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }

        Map<String, Object> extraParams = new HashMap<>();
        extraParams.put("rejectReason", rejectReason);

        // 修正：传入EventEnum.REJECT
        StateMachineContext context = new StateMachineContext(
                task.getTaskNo(), task.getStatus(), EventEnum.REJECT, operator);
        context.setExtraParams(extraParams);
        context.setRemark(rejectReason);

        TransitionRequest<Task> request = new TransitionRequest<>(
                task.getStatus(),
                EventEnum.REJECT,
                context,
                () -> entityManager.find(Task.class, taskId));

        TransitionResult<Task> result = stateMachineTemplate.sendEvent(request, Task.class);

        return result.getEntity();
    }
}